package org.devefx.myth.export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.devefx.myth.util.ResKit;
import org.devefx.myth.wdf.WDFParser;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class Start {
	
	static String CONFIG_TABLES = "tables";
	static String CONFIG_JDBC = "jdbc";
	
	static String JDBC_DRIVER_CLASS = "driver-class";
	static String JDBC_URL = "url";
	
	static String TABLES_QUERY = "query";
	static String TABLES_SOURCES = "sources";
	static String TABLES_OUTDIR = "outdir";
	
	static String toHex(int value, int len) {
		String hex = Integer.toHexString(value);
		int n = hex.length();
		for (int i = 0; i < len - n; i++) {
			hex = "0" + hex;
		}
		return hex.toUpperCase();
	}
	
	public static void main(String[] args) throws Exception {
		
		String configName = "export-config.json";
		
		String configText = ResKit.getResourceAsString(configName);
		
		JSONObject config = JSON.parseObject(configText);
		
		JSONArray tables = config.getJSONArray(CONFIG_TABLES);
		if (tables.isEmpty()) {
			System.err.println("No member of the tables: " + configName);
			return;
		}
		
		String base_indir = config.getString("base-indir");
		String base_outdir = config.getString("base-outdir");
		JSONObject jdbc = config.getJSONObject(CONFIG_JDBC);
		if (jdbc.containsKey(JDBC_DRIVER_CLASS)) {
			Class.forName(jdbc.getString(JDBC_DRIVER_CLASS));
		}
		Properties props = new Properties();
		String url = jdbc.getString(JDBC_URL);
		for (Map.Entry<String, Object> entry : jdbc.entrySet()) {
			props.put(entry.getKey(), entry.getValue());
		}
		
		Connection conn = DriverManager.getConnection(url, props);
		
		Map<String, WDFParser> parsers = new HashMap<String, WDFParser>();
		
		for (int i = 0; i < tables.size(); i++) {
			JSONObject table = tables.getJSONObject(i);
			
			JSONArray sources = table.getJSONArray(TABLES_SOURCES);
			String outdir = base_outdir + table.getString(TABLES_OUTDIR);

			File dir = new File(outdir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			
			StringBuffer buf = new StringBuffer();
			
			String sql = table.getString(TABLES_QUERY);
			PreparedStatement stmt = conn.prepareStatement(sql);
			ResultSet rs = stmt.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			int count = metaData.getColumnCount();
			while (rs.next()) {
				for (int j = 0; j < count; j++) {
					int id = rs.getInt(j + 1);
					String name = metaData.getColumnName(j + 1);
					boolean is_exist = false;
					for (int k = 0; k < sources.size(); k++) {
						String source = base_indir + sources.getString(k);
						WDFParser parser = parsers.get(source);
						if (parser == null) {
							parser = new WDFParser();
							parser.open(source);
							parsers.put(source, parser);
						}
						byte[] data = parser.read(id);
						if (data != null) {
							
							File file = new File(dir.getPath() + "/" + toHex(id, 8) + ".was");
							OutputStream out = new FileOutputStream(file);
							out.write(data);
							out.flush();
							out.close();
							
							is_exist = true;
							break;
						}
					}
					if (!is_exist) {
						System.out.println("not found id: " + id + " in " + sources);
						buf.append("[" + name + "]not found id: " + id + " in " + sources + "\n");
					}
				}
			}
			
			OutputStream out = new FileOutputStream(base_outdir + "error.txt");
			out.write(buf.toString().getBytes());
			out.flush();
			out.close();
			
		}
		
	}
	
	
	
}
